// pages/device/device.js
Page({
  data: {
    online:'在线',//设备在线状态
    alarm:'正常',
    deviceName:'ESP8266',
    wifiSwitch:true,//wifi开关
    fanSwitch:'XX10',//风扇开关
    irriogationPumpStatus:false,//水泵开关
    lightStatus:'XX20',//灯光开关
    plants:[],
    plantIds: [], // 新增一个数组用于存储植物的id
    selectedPlantIndex: 0, // 默认选择第一个盆栽
    temperatureTarget: 25, // 默认温度目标值
    humidityTarget: 50, // 默认湿度目标值
    co2ValueTarget:56,
    lightLuxTarget:1128,
    autoSwitch:false,
    sendTimers: []
  },
  onLoad: function () {
    this.fetchStatus();
    this.fetchPlants();
    this.initStatusFromBackend();
  },
  fetchPlants: function () {
    wx.request({
      url: 'http://120.26.231.14:8080/plantinstance/1', 
      method: 'GET',
      header: {
        token: wx.getStorageSync('token')
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === '1') {
          const processedPlants = res.data.data.map((plant,index) => ({
            id:plant.id,
            displayId: `${index + 1}`// 生成前端显示的标号
          }));
          const plantIds = processedPlants.map(plant => plant.displayId); // 用于 picker 的显示
          console.log('Processed Plants:', processedPlants); // 打印处理后的数据
          this.setData({
            plants: processedPlants,
            plantIds: plantIds // 设置植物id数组
          });
        } else {
          console.error('获取绿植信息:', res.statusCode, res.data);
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
      }
    });
  },
  onPickerChange: function (e) {
    const index = e.detail.value;
    const selectedPlant = this.data.plants[index];
    this.setData({
      selectedPlantIndex: index,
      selectedPlantId: selectedPlant.id // 记录选中的植物ID
    });
    // 异步操作如网络请求 (wx.request) 通常不会按照顺序执行
    this.fetchDeviceName();

    // 延迟0.1秒执行
    setTimeout(() =>{
      this.initStatusFromBackend();
      this.fetchStatus();
    },100);
    // 设置全局变量
    getApp().setGlobalData('selectedPlantId', selectedPlant.id);
    getApp().setGlobalData('selectedPlantDisplayId', selectedPlant.displayId);
    console.log('选择的绿植id:', getApp().getGlobalData('selectedPlantId'));
    console.log('绿植的展示编号:', getApp().getGlobalData('selectedPlantDisplayId'));
  },
  showPicker: function () {
    this.setData({
      pickerVisible: true
    });
  },
  fetchDeviceName:function(){
    const plantid = this.data.selectedPlantId;
    wx.request({
      url: 'http://120.26.231.14:8080/device/getDeviceName/'+plantid,
      method: 'GET',
      header: {
        token: wx.getStorageSync('token')
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === '1') {
          const devicename=res.data.data;
          this.setData({
            deviceName:devicename,
          });
          console.log('获取设备名称:', this.data.deviceName);
        } else {
          console.error('设备名称获取失败:', res.statusCode, this.devicename);
        }
      }
    })
  },
  // 查询设备在线状态
  fetchStatus: function() {
    console.log('获取设备状态之前：',this.data.deviceName);
    wx.request({
      url: 'http://120.26.231.14:8080/device/status/'+this.data.deviceName,
      method: 'GET',
      header: {
        token: wx.getStorageSync('token')
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data.code =='1') {
          console.log(res.data);
          const data = res.data.data.body.data.status === 'ONLINE'?'在线':'离线' ;
          this.setData({
              online:data
            });
          console.log('设备状态：',this.data.deviceName,data);
        } else {
          console.error('Failed to fetch status:', res.statusCode, res.data);
        }
      },
      fail: (err) => {
        console.error('Request failed:', err);
      }
    })
  },
  // 初始化各个开关状态
  initStatusFromBackend: function(){
    wx.request({
      url: 'http://120.26.231.14:8080/device/found/'+this.data.deviceName,
      method: 'GET',
      header: {
        token: wx.getStorageSync('token')
      },
      success: (res) => {
        if (res.statusCode === 200) {
          const data = res.data.data.body.data.list.propertyStatusInfo;
          const parsedData = {};
          console.log('设备初始化：',this.data.deviceName);
          data.forEach(item => {
            // 对照返回的json数据，与物模型定义相匹配
            if (item.identifier === 'FanSwitch') {
              parsedData.fanSwitch = item.value === 'XX11';//XX11代表开启
            } else if (item.identifier === 'WifiSwitch') {
              parsedData.wifiSwitch = item.value === 'XX01'; // XX01代表开启
            } else if (item.identifier === 'IrrigationPumpStatus') {
              parsedData.irriogationPumpStatus = item.value === '1';
            } else if (item.identifier === 'LightStatus'){
              parsedData.lightStatus = item.value === 'XX21';//XX21代表开启灯光
            } else if(item.identifier === 'TargetTemperature'){
              parsedData.temperatureTarget = item.value;
            } else if(item.identifier === 'TargetSoilMoisture'){
              parsedData.humidityTarget = item.value;
            } else if(item.identifier === 'TargetCO2Value'){
              parsedData.co2ValueTarget = item.value;
            } else if(item.identifier === 'TargetLightLux'){
              parsedData.lightLuxTarget = item.value;
            }
          });
          this.setData(parsedData);
          console.log('成功获取设备最新状态：',parsedData);
        } else {
          console.error('Failed to fetch status:', res.statusCode, res.data);
        }
      },
      fail: (err) => {
        console.error('Request failed:', err);
      }
    })
  },
  // 发送状态信息
  sendAllStatusesToBackend: function () {
    const deviceStatus = {
      id:3,
      name:this.data.deviceName,
      fanSwitch: this.data.fanSwitch ? 'XX11' : 'XX10',
      wifiSwitch: this.data.wifiSwitch ? 'XX01' : 'XX00', // XX00代表关闭
      irriogationPumpStatus: this.data.irriogationPumpStatus ? 1 : 0,
      lightStatus:this.data.lightStatus ? 1 : 0,
      targetTemperature:this.data.temperatureTarget,
      targetSoilMoisture:this.data.humidityTarget,
      targetCo2Value:this.data.co2ValueTarget,
      targetLightLux:this.data.lightLuxTarget
    };
    wx.request({
      url: 'http://120.26.231.14:8080/device/set',//不要把请求弄错了 是http 不是https
      method: 'PUT',
      data: deviceStatus,
      header: {
        token: wx.getStorageSync('token')
      },
      success: (res) => {
        if (res.statusCode === 200) {
          console.log('All statuses updated successfully:', deviceStatus);
        } else {
          console.error('Failed to update all statuses:', res.statusCode, res.data);
        }
      },
      fail: (err) => {
        console.error('Request failed:', err);
      }
    });
  },
  // wifi开关
  handleWifiChange: function (e) {
    const newStatus = e.detail.value;
    this.setData({ wifiSwitch: newStatus });
    
    for (let i = 0; i < 10; i++) {  
      this.sendAllStatusesToBackend();
      console.log("设置wifi开关:",newStatus);
    }
    
    this.clearSendTimers();// 清除之前的定时器
    // 设置新的定时器
    const firstSendTimer = setTimeout(() => {
      this.initStatusFromBackend();//获取状态
    }, 500); 
    this.setData({
      sendTimers: [firstSendTimer]
    });
  },
  // 风扇开关
  handleFanChange: function (e) {
    const newStatus = e.detail.value;
    this.setData({ fanSwitch: newStatus });
    for(let i = 0;i < 10 ;i++)
    {
      this.sendAllStatusesToBackend();
      console.log("设置风扇开关:",newStatus);
    }
  //  this.clearSendTimers();

  //  const firstSendTimer = setTimeout(() => {
  //    this.sendAllStatusesToBackend();
  //    this.sendAllStatusesToBackend();
  //    this.sendAllStatusesToBackend();
  //  }, 1000); // 第一次发送延迟1秒

  //  const secondSendTimer = setTimeout(() => {
  //    this.sendAllStatusesToBackend();
  //  }, 1000); // 第二次发送延迟2秒

  //  // 保存定时器句柄
  //  this.setData({
  //    sendTimers: [firstSendTimer, secondSendTimer]
  //  });
  },
  // 清除定时器
  clearSendTimers: function () {
    this.data.sendTimers.forEach(timer => {
      clearTimeout(timer);
    });
  },
  // 水泵开关
  handlePumpChange: function (e) {
    const newStatus = e.detail.value;
    this.setData({ irriogationPumpStatus: newStatus });
    this.sendAllStatusesToBackend();
  },
  // 灯光开关
  handleLightChange: function (e){
    const newStatus = e.detail.value;
    this.setData({ lightStatus: newStatus });
    this.sendAllStatusesToBackend();
  },
  //自动调节
  autoChange: function(e){
    const newStatus = e.detail.value;
    this.setData({ autoSwitch: newStatus });
    const deviceStatus = {
      id:3,
      name:this.data.deviceName,
      targetTemperature:this.data.temperatureTarget,
      targetSoilMoisture:this.data.humidityTarget,
      targetCo2Value:this.data.co2ValueTarget,
      targetLightLux:this.data.lightLuxTarget
    };
    wx.request({
      url: 'http://120.26.231.14:8080/device/setAuto',
      method: 'POST',
      data: deviceStatus,
      header: {
        token: wx.getStorageSync('token')
      },
      success: (res) => {
        if (res.statusCode === 200) {
          console.log('set AutoControl successfully:', deviceStatus);
        } else {
          console.error('Failed to set AutoControl:', res.statusCode, res.data);
        }
      },
      fail: (err) => {
        console.error('Request failed:', err);
      }
    });
  },
  // 目标值设定
  onTemperatureChange: function (e) {
    const value = e.detail.value;
    this.setData({ temperatureTarget: value });
  },

  onHumidityChange: function (e) {
    const value = e.detail.value;
    this.setData({ humidityTarget: value });
  },
   onLightChange: function (e) {
    const value = e.detail.value;
    this.setData({ lightLuxTarget: value });
  },

   onco2ValueChange: function (e) {
    const value = e.detail.value;
    this.setData({ co2ValueTarget: value });
  },
  saveTargets: function () {
    const { temperatureTarget, humidityTarget,co2ValueTarget,lightLuxTarget } = this.data;
    
    // 保存目标值
    wx.setStorageSync('temperatureTarget', temperatureTarget);
    wx.setStorageSync('humidityTarget', humidityTarget);
    wx.setStorageSync('co2ValueTarget', co2ValueTarget);
    wx.setStorageSync('lightLuxTarget', lightLuxTarget);

    console.log()
    // 发送目标值到设备
    this.sendAllStatusesToBackend();
  },
  onReady() {

  },

  onShow() {
    this.initStatusFromBackend();
    this.fetchStatus();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    // this.refreshData();

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
     // 当滚动到底部时触发
    //  this.refreshData();
  },
  refreshData: function () {
    // 上拉刷新
    this.fetchPlants();
  },

})